/*
 */

package com.ingenic.glass.camera.gallery;
import com.ingenic.glass.camera.CameraAppImpl;
import com.ingenic.glass.camera.R;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.MotionEvent;
import android.widget.GestureDetector;
import android.widget.GestureDetector.SimpleOnGestureListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AdapterPagedView.OnDownSlidingBackListener;
import android.widget.AdapterPagedView.OnItemClickListener;
import android.widget.AdapterPagedView.OnItemLongPressListener;
import android.widget.AdapterPagedView.OnPageSelectedListener;
import android.widget.AdapterPagedView;
import android.widget.MenuView;
import android.database.Cursor;
import android.text.format.DateFormat;
import android.view.ViewGroup.LayoutParams;

import java.lang.ref.WeakReference;
import java.util.Collections;  
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.io.File;

import android.view.View.OnTouchListener;

import com.ingenic.glass.camera.PhotoActivity;
import com.ingenic.glass.camera.CameraAppImpl;

import android.content.Intent;
/**
 * The GalleryPicker activity.
 */

public class GalleryPicker extends NoSearchActivity
        implements OnItemClickListener, OnItemLongPressListener
		   , OnDownSlidingBackListener, OnPageSelectedListener{

    private static final String TAG = "GalleryPicker";
    private static final int MESSAGE_ITEM_LIST_CHANGED = 1;
    private static final int MESSAGE_SCAN_COMPLETED = 2;
    private AdapterPagedView mPagedView;
    private MenuView mMenuView;
    private ArrayList<Item> mItemList = new ArrayList<Item>();   
    private ProgressBar mGallerypickerPB = null;
    private boolean mImageScanning = true;
    private boolean mVideoScanning = true;
    private ShareModule mShareModule = null;
    private Thread mImageWorkerThread; //thread :get image and show 
    private Thread mVideoWorkerThread;//thread :get video thumbnail and show 
    private MyBroadcastReceiver mReceiver;
    private boolean mUnmounted;
    private int mWindowsWidth = 0;
    private int mWindowsHeight = 0;
    private static final int FIRST_PAGE = 0;
    private GestureDetector mGestureDetector;
    private final String COMMAND_DELETE="删除";
    private final String COMMAND_SHARE="分享";
    private final String COMMAND_PLAY="播放";
    private final String COMMAND_NEXT="下一个";
    private final String COMMAND_LAST="上一个";
    private final int COMMAND_EXIT = R.string.cmd_exit;
    private final String [] VOICE_CMDS={COMMAND_DELETE,COMMAND_PLAY,COMMAND_NEXT,COMMAND_LAST};
    private int mGallerySelectMode; // 0:camera,1:other
    private GalleryAdapter mAdapter;
    private int mSelectedIndex = 0;
    private int mDefaultListSize ;
    private LinearLayout mSwitchLayout;
    private Object mLock = new Object();
    private MyHandler mHandler ;
    private static class MyHandler extends Handler {
	    WeakReference<Activity > mActivityReference;
	    
	    MyHandler(Activity activity) {
		    mActivityReference= new WeakReference<Activity>(activity);
	    }
	    
	    @Override
		    public void handleMessage(Message msg) {
		    final GalleryPicker mGalleryPicker = (GalleryPicker)mActivityReference.get();
		    if (mGalleryPicker != null) {
			    switch(msg.what){
			    case MESSAGE_ITEM_LIST_CHANGED:
				    if (mGalleryPicker.getIntent().getBooleanExtra("from_camera",false) 
					&& mGalleryPicker.mGallerypickerPB.getVisibility() == View.VISIBLE){
					    //如果是从拍照界面进入，从第二页开始显示
					    mGalleryPicker.mPagedView.setCurrentScreen(1);
				    }
				    
				    if((mGalleryPicker.mItemList.size() - mGalleryPicker.mDefaultListSize) > 0 
				       && mGalleryPicker.mGallerypickerPB.getVisibility() == View.VISIBLE){ 
					    //make sure excute one time 
					    mGalleryPicker.addVoiceCommand();
					    mGalleryPicker.mAdapter.notifyDataSetChanged();
					    Log.d(TAG,"progress gone--------------");
					    mGalleryPicker.mGallerypickerPB.setVisibility(ProgressBar.GONE);
				    }
				    break;
			    case MESSAGE_SCAN_COMPLETED:
				    if(mGalleryPicker.scanMediaComplete()){
					    mGalleryPicker.mAdapter.notifyDataSetChanged();
					    switch (mGalleryPicker.mGallerySelectMode){
					    case CameraAppImpl.OTHER:
						    if(mGalleryPicker.mItemList.size() == 0)
							    mGalleryPicker.showNoImagesView();
						    else  mGalleryPicker.mGallerypickerPB
								  .setVisibility(ProgressBar.GONE);
						    break;
					    case CameraAppImpl.PICTURE:
					    case CameraAppImpl.VIDEO:
						    if (mGalleryPicker.mDefaultListSize 
							== mGalleryPicker.mItemList.size()){ 
							    //如果扫描后mItemList的长度为0，则此时相册的相机中没有媒体文件
							    mGalleryPicker.showNoImagesView();
						    }
						    break;
					    }
				    }
				    break;
			    }	  
		    }
	    }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
	mWindowsWidth = getWindowManager().getDefaultDisplay().getWidth();  
	mWindowsHeight = getWindowManager().getDefaultDisplay().getHeight();
	mHandler = new MyHandler(this);
	mReceiver = new MyBroadcastReceiver(this);
	if (CameraAppImpl.DEBUG)
	    Log.d(TAG,"--onCreate in mWindowsWidth="+mWindowsWidth+" mWindowsHeight="+mWindowsHeight);

	ViewGroup root  = (ViewGroup) findViewById(R.id.main);
	View layout=getLayoutInflater().inflate(R.layout.gallerypicker,null);
	layout.setLayoutParams(new LayoutParams(mWindowsWidth, mWindowsHeight));
	root.addView(layout);
	mPagedView = (AdapterPagedView) layout.findViewById(R.id.pagedView);
	mPagedView.setOnItemClickListener(this);
	mPagedView.setOnItemLongPressListener(this);
	mPagedView.setOnDownSlidingBackListener(this);
	mPagedView.setOnPageSelectedListener(this);
	mPagedView.setFlyFlip(true);
    mGallerypickerPB = (ProgressBar) layout.findViewById(R.id.gallerypicker_pb);
	mMenuView = new MenuView(this);
	mMenuView.addMenuItemInfo(getResources().getString(R.string.delete));
	root.addView(mMenuView);
	mMenuView.setVisibility(View.GONE);
	mSwitchLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.switching,null);
	mSwitchLayout.setLayoutParams(new LayoutParams(mWindowsWidth, mWindowsHeight));
	root.addView(mSwitchLayout);
	mShareModule = ShareModule.getInstance(getApplicationContext());
        ensureOSXCompatibleFolder();
	boolean isFromCamera = getIntent().getBooleanExtra("from_camera",false);
	mDefaultListSize  =  isFromCamera ? 1 : 0;
	mAdapter = new GalleryAdapter(GalleryPicker.this, mItemList);
	mPagedView.setAdapter(mAdapter);
	
	if (isFromCamera){
	    /** 
	     *  正在切换的界面,用于在拍照界面左滑到相册的过度.
	     *  必须保持在第一页
	     **/
	    Item item = new Item(Long.MAX_VALUE,null,null,null,Long.MAX_VALUE,null);
	    synchronized (mLock) {
		    mItemList.add(item);
	    }
	}
	mGestureDetector = new GestureDetector(this, new MySimpleGestureDetectorListener(this));
	mGallerySelectMode=getIntent().getIntExtra("mode",0);
	mGallerypickerPB.setVisibility(ProgressBar.VISIBLE);
	setUseTimeout(false);
	startWorkerRun();
    }

    View mMediaScanningView;

  private View mNoImagesView;

    // Show/Hide the "no images" icon and text. Load resources on demand.
    private void showNoImagesView() {
        if (mNoImagesView == null) {
            ViewGroup root  = (ViewGroup) findViewById(R.id.main);
            mNoImagesView = getLayoutInflater().inflate(R.layout.gallerypicker_no_images, null);
	    mNoImagesView.setLayoutParams(new LayoutParams(mWindowsWidth, mWindowsHeight));
	    root.addView(mNoImagesView);
        }
        mPagedView.setVisibility(View.GONE);
	mNoImagesView.setOnTouchListener(new View.OnTouchListener() {
		public boolean onTouch(View v, MotionEvent event) {
		    return mGestureDetector.onTouchEvent(event); 
		}
	    });
	requestStopRecognize();
	ArrayList<String> voiceList = new ArrayList<String>();
	voiceList.add(getString(COMMAND_EXIT));					  
	setRecognizeCommands(voiceList);
	requestStartRecognize();
    }

    private void hideNoImagesView() {
        if (mNoImagesView != null) {
	    if (CameraAppImpl.DEBUG) Log.d(TAG,"--hide view");
            ViewGroup root  = (ViewGroup) findViewById(R.id.main);
	    root.removeView(mNoImagesView);
	    mPagedView.setVisibility(View.VISIBLE);
        }
    }

    private void addVoiceCommand() {

	    ArrayList<String> voiceList = new ArrayList<String>();
	    requestStopRecognize();
	    voiceList.add(getString(COMMAND_EXIT));
	    if (CameraAppImpl.PICTURE == mGallerySelectMode){
		    voiceList.add(COMMAND_SHARE);
	    }
	    for(int i=0;i<VOICE_CMDS.length;i++)
		    voiceList.add(VOICE_CMDS[i]);
	    setRecognizeCommands(voiceList);
	    requestStartRecognize();

   }

    // The storage status is changed, restart the worker or show "no images".
    private void rebake(boolean unmounted, boolean scanning) {
	if (CameraAppImpl.DEBUG) Log.d(TAG,"--rebake");
        if (unmounted == mUnmounted) return;
        abortImageWorker();
        abortVideoWorker();
        mUnmounted = unmounted;
        if (mUnmounted) {
            showNoImagesView();
        } else {
            hideNoImagesView();
            startImageWorker();
            startVideoWorker();
        }
    }

    // This is called when we receive media-related broadcast.
    private void onReceiveMediaBroadcast(Intent intent) {
        String action = intent.getAction();
	Uri uri = intent.getData();
        if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
	    if (CameraAppImpl.DEBUG) Log.d(TAG,"--onReceiveMediaBroadcast 1");
            // SD card available
            // TODO put up a "please wait" message
        } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
            // SD card unavailable
	    if (CameraAppImpl.DEBUG) Log.d(TAG,"--onReceiveMediaBroadcast 2");
            rebake(true, false);
        } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED) 
		   && uri.toString().equals(CameraAppImpl.SCAN_EXTERNAL_URI)) {
	    if (CameraAppImpl.DEBUG) Log.d(TAG,"--onReceiveMediaBroadcast 4");
            rebake(false, false);
        } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
	    if (CameraAppImpl.DEBUG) Log.d(TAG,"--onReceiveMediaBroadcast 5");
            rebake(true, false);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
	if (CameraAppImpl.DEBUG) Log.d(TAG,"--onStop in");
        unregisterReceiver(mReceiver);
	    finish();
    }

    @Override
	protected void onDestroy() {
	super.onDestroy();	
	if (CameraAppImpl.DEBUG)
	    Log.d(TAG, "--onDestory called.");
    mItemList.clear();
	abortImageWorker();
	abortVideoWorker();
	if (mAdapter != null)
		mAdapter.cleanBitmapList();
    }

    @Override
    public void onStart() {
        super.onStart();
	if (CameraAppImpl.DEBUG) Log.d(TAG,"--onStart in");
        // install an intent filter to receive SD card related events.
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
        intentFilter.addDataScheme("file");

	registerReceiver(mReceiver, intentFilter);
	// Assume the storage is mounted and not scanning.
	mUnmounted = false;

    }

    // This is used to stop the worker thread.
    volatile boolean mImageAbort = false;
    volatile boolean mVideoAbort = false;

    // Create the worker thread.
    private void startImageWorker() {
        mImageAbort = false;
        mImageWorkerThread = new Thread("GalleryPicker ImageWorker") {
            @Override
            public void run() {
		imageWorkerRun();
            }
        };
        BitmapManager.instance().allowThreadDecoding(mImageWorkerThread);
        mImageWorkerThread.start();
    }
    private void abortImageWorker() {
        if (mImageWorkerThread != null) {
            BitmapManager.instance().cancelThreadDecoding(mImageWorkerThread, getContentResolver());
            mImageAbort = true;
            try {
                mImageWorkerThread.join();
            } catch (InterruptedException ex) {
                Log.e(TAG, "join interrupted");
            }
            mImageWorkerThread = null;
            // Remove all runnables in mHandler.
            // (We assume that the "what" field in the messages are 0
            // for runnables).
            mHandler.removeMessages(0);
        }
    }
   private void startVideoWorker() {
        mVideoAbort = false;
        mVideoWorkerThread = new Thread("GalleryPicker VideoWorker") {
            @Override
            public void run() {	    
                videoWorkerRun();
            }
        };
        BitmapManager.instance().allowThreadDecoding(mVideoWorkerThread);
        mVideoWorkerThread.start();
    }

    private void abortVideoWorker() {
        if (mVideoWorkerThread != null) {
            BitmapManager.instance().cancelThreadDecoding(mVideoWorkerThread, getContentResolver());
            mVideoAbort = true;
            try {
                mVideoWorkerThread.join();
            } catch (InterruptedException ex) {
                Log.e(TAG, "join interrupted");
            }
            mVideoWorkerThread = null;
            // Remove all runnables in mHandler.
            // (We assume that the "what" field in the messages are 0
            // for runnables).
            mHandler.removeMessages(0);
        }
    }

    // This is run in the worker thread.
    private void imageWorkerRun() {
        if (mImageAbort) return;
	final ImageGetter ig = new ImageGetter(getContentResolver(),Images.Media.EXTERNAL_CONTENT_URI,
					 CameraAppImpl.SORT_DESCENDING,null);
	final Cursor cursor = ig.createCursor(mGallerySelectMode);
	if (cursor != null && cursor.moveToFirst()) {
	        int imageCount = cursor.getCount();
		if (CameraAppImpl.DEBUG)Log.d(TAG,"image cursor count="+imageCount);
		do {
			if (mImageAbort){
				cursor.close();
				return;
			}
			final Item it = ig.getImage(cursor);
			if (it != null) {
				synchronized (mLock) {			
					mItemList.add(it);
				}
				if(imageCount >= 500 && cursor.getPosition() == 50){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}else if(imageCount >=200 && imageCount < 500 && cursor.getPosition()==10){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}else if(imageCount<200){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}
			}
		}while(cursor.moveToNext());
	}
	if (cursor != null) cursor.close(); 
	mImageScanning = false;
	mHandler.sendEmptyMessage(MESSAGE_SCAN_COMPLETED);
    }

    // This is run in the worker thread.
    private void videoWorkerRun() {
        if (mVideoAbort) return;
	//get video Thumbnails
	if(CameraAppImpl.OTHER == mGallerySelectMode)
	    scanInternalVolume();
	final VideoGetter vig = new VideoGetter(getContentResolver(),
						    Uri.parse("content://media/external/video/media"),
						    CameraAppImpl.SORT_DESCENDING,null);
	final Cursor cursor = vig.createCursor(mGallerySelectMode);
	if (cursor != null && cursor.moveToFirst()) {
	        int videoCount = cursor.getCount();
		if (CameraAppImpl.DEBUG)Log.d(TAG,"video cursor count="+videoCount);
		do {
			if (mVideoAbort){
				cursor.close();
				return;
			}
			final Item it = vig.getImage(cursor);
			if (it != null) {
				synchronized (mLock) {
					mItemList.add(it);
				}
				if(videoCount >= 500 && cursor.getPosition() == 50){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}else if(videoCount >=200 && videoCount < 500 && cursor.getPosition()==10){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}else if(videoCount<200){
				    mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
				}
			}
		} while (cursor.moveToNext());
	}
	if (cursor != null) cursor.close(); 
	mVideoScanning = false;
	mHandler.sendEmptyMessage(MESSAGE_SCAN_COMPLETED);
    }

	private boolean scanMediaComplete(){
	    switch (mGallerySelectMode){
	    case CameraAppImpl.PICTURE:
		return !mImageScanning;
	    case CameraAppImpl.VIDEO:
		return !mVideoScanning;
	    case CameraAppImpl.OTHER:
		return !mImageScanning && !mVideoScanning;
	    }	    
	    return false;
	}
    
    private void scanInternalVolume(){
	VideoGetter vig = new VideoGetter(getContentResolver(),
						    Uri.parse("content://media/internal/video/media"),
						    CameraAppImpl.SORT_DESCENDING,null);
	Cursor cursor = vig.createCursor(mGallerySelectMode);
	if(cursor != null && cursor.moveToFirst()){
	    do{
		final Item it = vig.getImage(cursor);
		if (it != null) {
			synchronized (mLock) {
				mItemList.add(it);
				mHandler.sendEmptyMessage(MESSAGE_ITEM_LIST_CHANGED);
			}
		}
	    } while (cursor.moveToNext());
	}

	if (cursor != null) cursor.close(); 
	mHandler.sendEmptyMessage(MESSAGE_SCAN_COMPLETED);
    }
    
    private void startWorkerRun(){
	    switch (mGallerySelectMode){
	    case CameraAppImpl.PICTURE:
		    startImageWorker();
		    break;
	    case CameraAppImpl.VIDEO:
		    startVideoWorker();
		    break;
	    case CameraAppImpl.OTHER:
		    startImageWorker();
		    startVideoWorker();
		    break;
	    } 
    }

    // This is run in the main thread. from ImageManager.java
    public void ensureOSXCompatibleFolder() {
        File nnnAAAAA = new File(
            Environment.getExternalStorageDirectory().toString()
            + "/DCIM/100ANDRO");
        if ((!nnnAAAAA.exists()) && (!nnnAAAAA.mkdir())) {
            Log.e(TAG, "create NNNAAAAA file: " + nnnAAAAA.getPath()
                    + " failed");
        }
    }


    /*override from PageView*/
    @Override
    public void onItemClick(AdapterPagedView pagedView, View v, int position) {
	startVideo(position);
    }
    @Override
    public void onItemLongPress(AdapterPagedView pagedView, View v, int position) {
	if (CameraAppImpl.DEBUG) Log.d(TAG, "onItemLongPress in position=" + mMenuView.getVisibility());
	setUpMenu(position);
    }
    @Override
    public void onDownSlidingBack(AdapterPagedView pagedView) {
	if (CameraAppImpl.DEBUG)
	    Log.d(TAG, "OnDownSlidingBack in ");
	finish();

    }
    @Override
    public void onPageSelected(AdapterPagedView pagedView, View view, int position) {
            if (CameraAppImpl.DEBUG) Log.d(TAG, "onPageSelected in position=" + position);
	    boolean isFromCamera = getIntent().getBooleanExtra("from_camera",false);
	    if (position == 0 && isFromCamera && mPagedView.getVisibility()==View.VISIBLE){
		mSwitchLayout.setVisibility(View.VISIBLE);
		abortImageWorker();
		abortVideoWorker();
		Intent intent=new Intent(GalleryPicker.this,PhotoActivity.class);
		startActivity(intent);
		finish();
	    }
         mSelectedIndex = position;
    }
    private void setUpMenu(int position){
	final int longPressPosition=position;
	View v = mPagedView.getSelectedView();
	mMenuView.removeMenuItemInfo(getResources().getString(R.string.share));
	synchronized (mLock) {
		if (CameraAppImpl.PICTURE == mGallerySelectMode){
			mMenuView.addMenuItemInfo(getResources().getString(R.string.share));
		}
	}
	mMenuView.setVisibility(View.VISIBLE);	
	mMenuView.setOnClickListener(v, new MenuView.OnClickListener() {
		public void onClick(View v, int position) {
		    if(mMenuView.getVisibility() == View.GONE){
	       		return;
		    }
		    mMenuView.setVisibility(View.GONE);
		    if (position == 0) {
			deleteCurrentView(longPressPosition);
		    }
		    if (position == 1) {
			shareSyncToPhone(longPressPosition);				
		    }
		}
	    });
	mMenuView.setOnBackListener(v, new MenuView.OnBackListener() {
		public void onBack(View v) {
		    mMenuView.setVisibility(View.GONE);
		}
	    });
    }
    private void startVideo(int currentPosition) {
	    synchronized (mLock) {
		    if (currentPosition < 0 ||  currentPosition >= mItemList.size()) {
			    return ;
		    }
		    if (mItemList.get(currentPosition).MimeType.indexOf("video/") != -1) {
			    String file_path = "file://" + mItemList.get(currentPosition).DataPath;
			    if (CameraAppImpl.DEBUG) Log.d(TAG, "----file_path !" + file_path);
			    Intent intent;
			    intent = new Intent();
			    intent.setClass(this,MovieActivity.class);
			    intent.setDataAndType(Uri.parse(file_path), "video/*");
			    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);	    
			    startActivity(intent);
		    }
	    }
    }

    private void shareSyncToPhone(int currentPosition) {
	    synchronized (mLock) {
		    if (CameraAppImpl.DEBUG)
			    Log.d(TAG, "shareSyncToPhone in");
		    if (currentPosition < 0 ||  currentPosition >= mItemList.size()) {
			    return ;
		    }
		    // share
		    if (mShareModule != null) {
			    if (!mShareModule.sendData(mItemList.get(currentPosition).DataPath))
				    showToast(getResources().getString(R.string.share_failed));			
		    }
	    }
    }
    private void deleteCurrentView(int currentPosition) {
	    synchronized (mLock) {
		    if (CameraAppImpl.DEBUG)
			    Log.d(TAG, "deleteCurrentView in");
		    if (currentPosition < 0 ||  currentPosition >= mItemList.size()) {
			    return ;
		    }
		    // delete
		    if (getContentResolver().delete(mItemList.get(currentPosition).ContentUri, null, null) <= 0) {
			    Log.e(TAG, "-------deleteCurrentView faild");	    
		    }
		    mItemList.remove(currentPosition);
		    mAdapter.notifyDataSetChanged();
		    showToast(getResources().getString(R.string.delete_success));
		    if (mItemList.size() <= mDefaultListSize)
			    showNoImagesView();
	    }
    }
    private void showToast(String str){
	Toast toast = new Toast(this);
	View layout = getLayoutInflater().inflate(R.layout.toast, null);
	TextView toast_tv = null;
	toast_tv = (TextView) layout.findViewById(R.id.tv_toast);
	toast_tv.setText(str);
	toast.setView(layout);
	toast.show();
    }

    private static class MyBroadcastReceiver extends BroadcastReceiver{
	    WeakReference<Activity > mActivityReference;

	    MyBroadcastReceiver(Activity activity) {
		    mActivityReference= new WeakReference<Activity>(activity);
	    }
            @Override
            public void onReceive(Context context, Intent intent) {
		    final GalleryPicker mGalleryPicker = (GalleryPicker)mActivityReference.get();
		    if (mGalleryPicker != null) {
			    mGalleryPicker.onReceiveMediaBroadcast(intent);
		    }
            }
        }

    private static class MySimpleGestureDetectorListener extends GestureDetector.SimpleOnGestureListener{
	WeakReference<Activity > mActivityReference;

	MySimpleGestureDetectorListener(Activity activity) {
		mActivityReference= new WeakReference<Activity>(activity);
	}

	@Override
	     public boolean onSlideDown(boolean fromPhone){
		final GalleryPicker mGalleryPicker = (GalleryPicker)mActivityReference.get();
		if (mGalleryPicker != null) {
			mGalleryPicker.finish();
		}
		return true;
	}

	@Override
	     public boolean onSlideRight(boolean fromPhone){
		final GalleryPicker mGalleryPicker = (GalleryPicker)mActivityReference.get();
		if (mGalleryPicker != null) {
		      if (mGalleryPicker.getIntent().getBooleanExtra("from_camera",false)){
			      mGalleryPicker.mSwitchLayout.setVisibility(View.VISIBLE);
			      Intent intent=new Intent(mGalleryPicker,PhotoActivity.class);
			      mGalleryPicker.startActivity(intent);
			      mGalleryPicker.finish();
		      }
		}
		return true;
	}

    }

    /*******************for voice****************************/
    @Override
	protected boolean onCommandResult(String result, float score) {
	if (CameraAppImpl.DEBUG) Log.d(TAG, "onCommandResult " + result + " " + score);
	if (score > -15) {
	    boolean ret=true;
	    if(result.equals(COMMAND_DELETE)){
		deleteCurrentView(mPagedView.getCurScreen());
		ret=false;	
	    }else if(result.equals(COMMAND_SHARE)){
	            // Video does not support sharing
		    synchronized (mLock) {
			    if (-1 != mItemList.get(mSelectedIndex).MimeType.indexOf("video/")) {
				    Toast.makeText(GalleryPicker.this, R.string.share_video_notsupport, Toast.LENGTH_SHORT).show();
			    } else {
				    shareSyncToPhone(mPagedView.getCurScreen());
			    }
			    ret=false;		
		    }
	    }else if(result.equals(COMMAND_PLAY)){
		startVideo(mPagedView.getCurScreen());
		  // Image does not respond playing
		synchronized (mLock) {
			if(-1 != mItemList.get(mPagedView.getCurScreen()).MimeType.indexOf("video/")){
				ret = true;
			}else{
				ret = false;
			}
		}
	    }else if(result.equals(COMMAND_NEXT)){
		    synchronized (mLock) {
			    if(mPagedView.getCurScreen() != mItemList.size() - 1)
				    mPagedView.setCurrentScreen(mPagedView.getCurScreen()+1);
			    ret=false;
		    }
	    }else if(result.equals(COMMAND_LAST)){
		if(mPagedView.getCurScreen()!=0)
		    mPagedView.setCurrentScreen(mPagedView.getCurScreen()-1);
		ret=false;
	    }
	    return ret;							    
	} else {								    	    
	    return false;							    
	}									    
    }
    @Override
	protected boolean onExit(float score) {
	if (score > -15) {
	    finish();
	    return true;
	} else
	    return false;
    }
}


